package com.lab.schemeurl.url;

import android.net.Uri;
import android.text.TextUtils;

import java.util.LinkedHashMap;
import java.util.Set;

/**
 * Created by ak on 3/30/16.
 */
public class UrlBuilder {

    private LinkedHashMap<String, Object> keyValues = new LinkedHashMap<>();


    private Uri initUri;


    public UrlBuilder() {
    }

    public UrlBuilder(String url) {
        initUri = Uri.parse(url);
    }

    public UrlBuilder(Uri uri) {
        this.initUri = uri;
    }

    public void addObject(String key, String value) {
        keyValues.put(key, value);
    }

    public boolean contains(String key) {
        if (keyValues.containsKey(key)) {
            return true;
        } else {
            String parameterValue = initUri.getQueryParameter(key);
            if (!TextUtils.isEmpty(parameterValue)) {
                return true;
            } else {
                return false;
            }
        }
    }

    public String toUrl() {
        StringBuilder stringBuilder = new StringBuilder();
        if (initUri != null) {
            stringBuilder.append(initUri.toString());
            if (keyValues.size() == 0) {
                return stringBuilder.toString();
            }
            Set<String> parameterNames = initUri.getQueryParameterNames();
            if (parameterNames.size() == 0) {
                stringBuilder.append("?");
            } else {
                stringBuilder.append("&");
            }
            Set<String> keys = keyValues.keySet();
            int i = 0;
            for (String key : keys) {
                if (0 != i) {
                    stringBuilder.append("&");
                }
                stringBuilder.append(key);
                stringBuilder.append("=");
                stringBuilder.append(keyValues.get(key));
                i++;
            }
        }
        return stringBuilder.toString();
    }

}
